﻿using DzInfo.Model.FanWei;
using DzInfo.Model.KD;
using DzInfo.Tools;
using Kingdee.BOS.App.Core;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Business.DynamicForm.PlugIn.InitQuickImport;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Interaction;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Msg;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Resource;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Kingdee.K3.Core.SCM.STK;
using Kingdee.K3.FIN.App.Core;
using Kingdee.K3.SCM.Contracts;
using Kingdee.K3.SCM.ServiceHelper;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DzInfo.SerivesPlugin.GYD
{
    [Description("GYD库存销售订单保存锁库等功能"), HotUpdate]
    public class AutoYL : AbstractOperationServicePlugIn
    {
        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            var obj = e.DataEntitys.FirstOrDefault();
            if (obj == null) { return; }
            string billTypeNumber = obj["BillTypeId"] == null ? "" : (obj["BillTypeId"] as DynamicObject)["number"].ToString();
            if (billTypeNumber.Equals("XSDD001_SYS") || billTypeNumber.Equals("XSDD17_SYS") || billTypeNumber.Equals("XSDD005_SYS"))
            {
                DynamicObjectCollection rows = obj["SaleOrderEntry"] as DynamicObjectCollection;
                if (rows.Count <= 0) { return; }
                string opNumber = this.FormOperation.Operation;
                var oldNo = rows.Select(s => s["FoldBillno"].ToString());
                var oldSeq = rows.Select(s => Convert.ToInt64(s["FoldSeq"]));

                // 判断条件：oldNo全部为空/空白 且 oldSeq全部为0
                if (!(oldNo.All(string.IsNullOrWhiteSpace) && oldSeq.All(seq => seq == 0)))
                {
                    foreach (var row in rows)
                    {
                        decimal qty = Convert.ToDecimal(row["Qty"]);
                        string oldBillno = row["FoldBillno"].ToString();
                        long oSeq = Convert.ToInt64(row["FoldSeq"]);
                        decimal oldQty = GetOldQty(oldBillno, oSeq);
                        if (qty > oldQty)
                        {
                            if (opNumber.Equals("Save"))
                            {
                                e.CancelOperation = true;
                                AddOperateResult(this.OperationResult, "数量比源单可出数量大，不允许保存", "源单");
                                return;
                            }
                        }
                    }
                    if (opNumber.Equals("Audit"))
                    {
                        foreach (var row in rows)
                        {
                            decimal qty = Convert.ToDecimal(row["Qty"]);
                            string curMto = row["MtoNo"].ToString();
                            string oldMto = "";
                            string oldFid = "0";
                            List<long> ids = new List<long>();
                            string oldBillno = row["FoldBillno"].ToString();
                            long oSeq = Convert.ToInt64(row["FoldSeq"]);
                            DynamicObjectCollection oldInfo = GetOldInfo(oldBillno, oSeq);
                            if (oldInfo.Count > 0)
                            {
                                oldMto = oldInfo[0]["FMtoNo"].ToString().Trim();
                                oldFid = oldInfo[0]["FID"].ToString();
                                long id = Convert.ToInt64(oldInfo[0]["FENTRYID"]);
                                ids.Add(id);
                            }
                            var eids = ids.ToArray();
                            decimal oldQty = Convert.ToDecimal(oldInfo[0]["FQTY"]);
                            if (oldQty - qty > 0)
                            {
                                //审核时生成并生效源销售订单新变更单
                                var xSal = KDApi.SaveXSaleOrder("192.168.1.27", "681c2e087ee725", "T0013", "1234567", oldBillno, oldFid, eids);
                                //var xSal = KDApi.SaveXSaleOrder("127.0.0.1", "68045fb82012b7", "demo", "Aaron_7750", oldBillno, oldFid, eids);
                                if (xSal.IsSuccess)
                                {
                                    //AddOperateResult(this.OperationResult, xSal.Message, "销售变更");

                                    string xsJson = GetXsJson(xSal, qty, oldInfo);
                                    var xSalOrder = KDApi.Save(this.Context, "SAL_XORDER", xsJson);
                                    if (xSalOrder.Result.ResponseStatus.IsSuccess)
                                    {
                                        var tefpar = new
                                        {
                                            Ids = xSal.Datas[0].FID,
                                            InterationFlags = "SAL_CHECKPRICESOURCEFB"
                                        }
                                            ;
                                        var tef = KDApi.TakeEffect(this.Context, "SAL_XORDER", JsonConvert.SerializeObject(tefpar));
                                        //var subpar = new
                                        //{
                                        //    Ids = xSal.Datas[0].FID
                                        //};
                                        //var subRes = KDApi.Submit(this.Context, "SAL_XORDER", JsonConvert.SerializeObject(subpar));
                                        //if (subRes.Result.ResponseStatus.IsSuccess)
                                        //{

                                        //    var audRes = KDApi.Audit(this.Context, "SAL_XORDER", JsonConvert.SerializeObject(subpar));
                                        //    if (audRes.Result.ResponseStatus.IsSuccess)
                                        //    {

                                        //    }
                                        //}
                                    }
                                }
                                else
                                {
                                    //AddOperateResult(this.OperationResult, xSal.Message, "销售变更");
                                    e.CancelOperation = true;
                                    return;
                                }
                            }
                            else
                            {
                                //关闭订单行
                                List<object> pkes = new List<object>();
                                foreach (var pk in eids)
                                {
                                    pkes.Add(pk);
                                }
                                string data = KDApi.ExecuteParameter("", "", pkes.ToArray());
                                var res = KDApi.Execute(this.Context, KdFomId.SAL_SaleOrder.ToString(), "ToClose", data);
                            }
                            //如果计划跟踪号不相同，生成形态转换单，STK_StatusConvert
                            if (curMto != oldMto)
                            {
                                DynamicObject mat = row["MaterialId"] as DynamicObject;
                                long matId = mat == null ? 0 : Convert.ToInt64(mat["id"]);
                                string matNumber = mat == null ? "" : Convert.ToString(mat["number"]);
                                DynamicObject invOrg = row["StockOrgId"] as DynamicObject;
                                long orgId = invOrg == null ? 0 : Convert.ToInt64(invOrg["id"]);
                                string mtoNo = row["MtoNo"] == null ? "" : row["MtoNo"].ToString();
                                long stockId = 0;
                                DynamicObjectCollection inv = GetInvInfo(matId, orgId, oldMto);
                                if (inv.Count > 0)
                                {
                                    stockId = Convert.ToInt64(inv[0]["FSTOCKID"]);
                                }

                                var view = KingdeeTools.CreateBillView(this.Context, "STK_StatusConvert");
                                ViewSetVaue(view, curMto, oldMto, qty, stockId, matId);
                                //List<DynamicObject> objects = new List<DynamicObject>();
                                //objects.Add(view.Model.DataObject);
                                //var objs = AppServiceContext.SaveService.Save(this.Context, objects.ToArray());
                                // 调用保存操作
                                SaveObj(view);
                            }
                        }
                    }

                }
                // 条件成立，执行你的逻辑
                if (opNumber.Equals("Save") && (oldNo.All(string.IsNullOrWhiteSpace) && oldSeq.All(seq => seq == 0)))
                {
                    e.CancelOperation = CheckInv(rows, opNumber);
                    if (e.CancelOperation)
                    {
                        return;
                    }
                }
                if (opNumber.Equals("Audit"))
                {
                    //e.CancelOperation = CheckInv(rows, opNumber);
                    //if (e.CancelOperation)
                    //{
                    //    return;
                    //}
                    e.CancelOperation = SaveStockLock(rows);
                    if (e.CancelOperation)
                    {
                        return;
                    }
                }
                if (opNumber.Equals("UnAudit"))
                {
                    e.CancelOperation = SaveUnLock(rows);
                    if (e.CancelOperation)
                    {
                        return;
                    }
                }
            }
            base.BeginOperationTransaction(e);
        }

        private void SaveObj(IBillView view)
        {
            OperateOption saveOption = OperateOption.Create();
            IOperationResult saveResult = BusinessDataServiceHelper.Save(
                        this.Context,
                        view.BillBusinessInfo,
                        view.Model.DataObject,
                        saveOption,
                        "Save");
            if (saveResult == null)
            {
                view.ShowErrMessage("未知原因导致保存失败！");
                return;
            }
            else if (saveResult.IsSuccess == true)
            {// 保存成功，直接显示
             //this.View.ShowOperateResult(saveResult.OperateResult);

                object[] pkArray = (from p in saveResult.SuccessDataEnity select p[0]).ToArray();

                var submitResult = BusinessDataServiceHelper.Submit(this.Context, view.BillBusinessInfo, pkArray, "Submit", OperateOption.Create());
                if (submitResult.IsSuccess)
                {
                    var auditResult = BusinessDataServiceHelper.Audit(this.Context, view.BillBusinessInfo, pkArray, OperateOption.Create());
                    if (auditResult.IsSuccess)
                    {
                        view.ShowOperateResult(auditResult.OperateResult);
                    }
                }
            }
            else if (saveResult.InteractionContext != null
                    && saveResult.InteractionContext.Option.GetInteractionFlag().Count > 0)
            {// 保存失败，需要用户确认问题
                InteractionUtil.DoInteraction(view, saveResult, saveOption,
                    new Action<FormResult, IInteractionResult, OperateOption>((formResult, opResult, option) =>
                    {
                        // 用户确认完毕，重新调用保存处理
                        this.SaveObj(view);
                    }));
            }
            // 保存失败，显示错误信息
            if (saveResult.IsShowMessage)
            {
                saveResult.MergeValidateErrors();
                view.ShowOperateResult(saveResult.OperateResult);
                return;
            }
        }

        private void ViewSetVaue(IBillView view, string curMto, string oldMto, decimal qty, long stockId, long matId)
        {
            view.Model.BeginIniti();
            view.Model.CreateNewData();
            view.Model.EndIniti();
            view.Model.SetItemValueByNumber("FBillTypeID", "XTZH01_SYS", 0);
            view.Model.SetItemValueByID("FStockOrgId", 1, 0);
            view.Model.SetValue("FDate", DateTime.Now, 0);
            view.Model.ClearNoDataRow();
            view.Model.BatchCreateNewEntryRow("FEntity", 2);
            DynamicObjectCollection rows = view.Model.DataObject["StatusConvertEntry"] as DynamicObjectCollection;
            for (int i = 0; i < rows.Count; i++)
            {
                view.Model.SetItemValueByID("FMaterialId", matId, i);
                view.InvokeFieldUpdateService("FMaterialId", i);
                view.Model.SetValue("FConvertQty", qty, i);
                view.Model.SetItemValueByID("FStockId", stockId, i);
                view.InvokeFieldUpdateService("FStockId", i);
                if (i == 1)
                {
                    view.Model.SetValue("FConvertType", "B", i);
                    view.Model.SetValue("FMTONo", curMto, i);
                }
                else
                {
                    view.Model.SetValue("FMTONo", oldMto, i);
                }

            }
        }

        private string GetXsJson(Model.KD.XOrderReSult xSal, decimal qty, DynamicObjectCollection oldInfo)
        {
            decimal oldQty = Convert.ToDecimal(oldInfo[0]["FQTY"]);
            decimal newQty = oldQty - qty;
            XOrderSave xOrderSave = new XOrderSave();
            xOrderSave.IsDeleteEntry = "false";
            xOrderSave.Model = new XorderSaveModel();
            xOrderSave.Model.FID = xSal.Datas[0].FID;
            xOrderSave.Model.FSaleOrderEntry = new List<FSaleOrderEntryItem>();
            foreach (var erow in xSal.Datas[0].SaleOrderEntry)
            {
                FSaleOrderEntryItem fSaleOrderEntryItem = new FSaleOrderEntryItem();
                fSaleOrderEntryItem.FEntryID = erow.FEntryID;
                fSaleOrderEntryItem.FQty = newQty;
                xOrderSave.Model.FSaleOrderEntry.Add(fSaleOrderEntryItem);
            }
            return JsonConvert.SerializeObject(xOrderSave, Formatting.Indented);
        }

        /// <summary>
        /// 获取形态转换单JSON
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private string GetXdJson()
        {
            throw new NotImplementedException();
        }

        private DynamicObjectCollection GetOldInfo(string oldBillno, long oSeq)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T2.FBaseCanOutQty ,T1.FMtoNo,T0.FID,T1.FENTRYID ,T1.FQTY
            FROM T_SAL_ORDER T0
            JOIN T_SAL_ORDERENTRY T1 ON T1.FID=T0.FID
            JOIN T_SAL_ORDERENTRY_R T2 ON T2.FENTRYID=T1.FENTRYID
            WHERE T0.FBILLNO='{0}' AND T1.FSEQ={1}  ", oldBillno, oSeq);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private decimal GetOldQty(string oldBillno, long oSeq)
        {
            decimal qty = 0;
            string sql = string.Format(@"/*dialect*/ 
            SELECT T2.FBaseCanOutQty 
            FROM T_SAL_ORDER T0
            JOIN T_SAL_ORDERENTRY T1 ON T1.FID=T0.FID
            JOIN T_SAL_ORDERENTRY_R T2 ON T2.FENTRYID=T1.FENTRYID
            WHERE T0.FBILLNO='{0}' AND T1.FSEQ={1}  ", oldBillno, oSeq);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                qty = Convert.ToDecimal(doc[0][0]);
            }
            return qty;
        }

        private bool SaveUnLock(DynamicObjectCollection rows)
        {
            bool flag = false;
            List<LockStockArgs> stockArgList = new List<LockStockArgs>();

            foreach (var row in rows)
            {
                AddUnList(row, stockArgList);
            }
            if (stockArgList.Count > 0)
            {
                StockServiceHelper.SaveUnLockInfo(this.Context, stockArgList, "Inv");
            }
            else
            {
                flag = true;
            }

            return flag;
        }

        private void AddUnList(DynamicObject row, List<LockStockArgs> stockArgList)
        {
            decimal remainingQty = Convert.ToDecimal(row["Qty"]);
            if (remainingQty <= 0) return;

            DynamicObject mat = row["MaterialId"] as DynamicObject;
            long matId = mat?["id"] as long? ?? 0;
            string matNumber = mat?["number"]?.ToString() ?? "";

            DynamicObject invOrg = row["StockOrgId"] as DynamicObject;
            long orgId = invOrg?["id"] as long? ?? 0;

            string mtoNo = row["MtoNo"]?.ToString() ?? "";

            DynamicObjectCollection invRows = GetLockList(matId, orgId, mtoNo);
            var stockService = Kingdee.K3.SCM.Contracts.ServiceFactory.GetStockInvService(this.Context);

            foreach (var invRow in invRows)
            {
                if (remainingQty <= 0) break;

                string invFid = invRow["FID"].ToString();
                var invStock = stockService.GetInventoryDatas(this.Context, invFid, orgId);
                long invEntryId = GetEntryId(invFid);

                foreach (var inv in invStock)
                {
                    if (remainingQty <= 0) break;

                    decimal lockQty = inv.BaseLockQty;
                    if (lockQty <= 0) continue;

                    decimal unlockQty = Math.Min(lockQty, remainingQty);
                    remainingQty -= unlockQty;

                    stockArgList.Add(new LockStockArgs
                    {
                        ObjectId = "STK_Inventory",
                        FEntryID = invEntryId,
                        FInvDetailID = invFid,
                        UnLockQty = unlockQty,
                        UnLockBaseQty = unlockQty,
                        BillDetailID = ""
                    });
                }
            }
        }

        private long GetEntryId(string invFid)
        {
            string sql = string.Format(@"/*dialect*/ 
            SELECT T0.FENTRYID FROM T_PLN_RESERVELINKENTRY T0 WHERE T0.FSUPPLYINTERID='{0}'  ", invFid);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                return Convert.ToInt64(doc[0][0]);
            }
            else
            {
                return 0;
            }
        }

        private DynamicObjectCollection GetLockList(long matId, long orgId, string mtoNo)
        {
            //T0.FID, 即时库存内码
            //T0.FSTOCKID, 仓库
            //T0.FSTOCKSTATUSID, 库存状态
            //T0.FBASEQTY, 基本数量
            //T0.FOWNERTYPEID, 货主类型
            //T0.FOWNERID, 货主
            //T0.FKEEPERTYPEID, 保管者类型
            //T0.FKEEPERID, 保管者
            //T0.FBASEUNITID, 基本单位
            //T0.FSECUNITID 库存辅单位
            string sql = string.Format(@"/*dialect*/ 
            select 
            T0.FID,
            T0.FSTOCKID,
            T0.FSTOCKSTATUSID,
            T0.FBASEQTY,
            T0.FOWNERTYPEID,
            T0.FOWNERID,
            T0.FKEEPERTYPEID,
            T0.FKEEPERID,
            T0.FBASEUNITID,
            T0.FSECUNITID
            from T_STK_INVENTORY t0
            WHERE T0.FBASEQTY>0 AND T0.FSTOCKORGID={0} AND T0.FMATERIALID={1} AND T0.FMTONO='{2}'  ", orgId, matId, mtoNo);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private bool CheckInv(DynamicObjectCollection rows, string opNumber)
        {
            string message = "保存";
            if (opNumber == "Save")
            {
                message = "保存";
            }
            if (opNumber == "Audit")
            {
                message = "审核";
            }
            bool flag = false;
            foreach (var row in rows)
            {
                decimal qty = Convert.ToDecimal(row["Qty"]);
                DynamicObject mat = row["MaterialId"] as DynamicObject;
                long matId = mat == null ? 0 : Convert.ToInt64(mat["id"]);
                string matNumber = mat == null ? "" : Convert.ToString(mat["number"]);
                DynamicObject invOrg = row["StockOrgId"] as DynamicObject;
                long orgId = invOrg == null ? 0 : Convert.ToInt64(invOrg["id"]);
                string mtoNo = row["MtoNo"] == null ? "" : row["MtoNo"].ToString();
                decimal invQty = GetInvQty(matId, orgId, mtoNo);
                if (qty > invQty)
                {
                    AddOperateResult(this.OperationResult, $"物料：{matNumber}库存：{invQty}不够,不允许{message}！", "库存");
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        private decimal GetInvQty(long matId, long orgId, string mtoNo)
        {
            decimal invQty = 0;
            string sql = string.Format(@"/*dialect*/ 
            select SUM(T0.FBASEQTY) FBASEQTY 
            from T_STK_INVENTORY t0
            WHERE T0.FBASEQTY>0 AND T0.FSTOCKORGID={0} AND T0.FMATERIALID={1} AND T0.FMTONO='{2}'
            GROUP BY T0.FSTOCKORGID,T0.FMATERIALID,T0.FMTONO  ", orgId, matId, mtoNo);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (doc.Count > 0)
            {
                invQty = Convert.ToDecimal(doc[0][0]);
            }
            return invQty;
        }

        private bool SaveStockLock(DynamicObjectCollection rows)
        {
            bool flag = false;
            List<LockStockArgs> list = new List<LockStockArgs>();
            foreach (var row in rows)
            {
                AddList(row, list);
            }
            if (list.Count > 0 && !flag)
            {
                StockServiceHelper.SaveLockInfo(base.Context, list);
                AddOperateResult(this.OperationResult, "锁库成功", "锁库");
            }
            else
            {
                AddOperateResult(this.OperationResult, "锁库失败", "锁库");
                flag = true;
            }
            return flag;
        }

        private void AddList(DynamicObject row, List<LockStockArgs> list)
        {
            decimal qty = Convert.ToDecimal(row["Qty"]);
            DynamicObject mat = row["MaterialId"] as DynamicObject;
            long matId = mat == null ? 0 : Convert.ToInt64(mat["id"]);
            string matNumber = mat == null ? "" : Convert.ToString(mat["number"]);

            DynamicObject invOrg = row["StockOrgId"] as DynamicObject;
            long orgId = invOrg == null ? 0 : Convert.ToInt64(invOrg["id"]);

            string mtoNo = row["MtoNo"]?.ToString() ?? "";
            long bomId = 0;
            var bomObj = row["BomId"] as DynamicObject;
            if (bomObj != null && bomObj["id"] != null)
            {
                bomId = Convert.ToInt64(bomObj["id"]);
            }

            // 提前获取物料计划模式
            string planMode = "0";
            if (mat != null && mat["MaterialPlan"] is DynamicObjectCollection materialPlan &&
                materialPlan.Count > 0 && materialPlan[0]["PlanMode"] != null)
            {
                planMode = materialPlan[0]["PlanMode"].ToString() == "1" ? "1" : "0";
            }

            // 获取库存信息
            DynamicObjectCollection invRow = GetInvInfo(matId, orgId, mtoNo);
            decimal remainingQty = qty;

            foreach (var item in invRow)
            {
                if (remainingQty <= 0) break; // 需求已满足，提前终止

                decimal invQty = item["FBASEQTY"] == null ? 0 : Convert.ToDecimal(item["FBASEQTY"]);
                if (invQty <= 0) continue; // 无效库存跳过

                // 计算本次实际锁库数量
                decimal lockQty = Math.Min(invQty, remainingQty);

                // 创建锁库参数
                LockStockArgs stockArg = new LockStockArgs
                {
                    ObjectId = "STK_Inventory",
                    BillId = item["FID"]?.ToString() ?? "",
                    FInvDetailID = item["FID"]?.ToString() ?? "",
                    StockOrgID = orgId,
                    DemandOrgId = orgId,
                    MaterialID = matId,
                    DemandMaterialId = matId,
                    IsMto = planMode,
                    MtoNo = mtoNo,
                    BOMID = bomId,
                    STOCKID = item["FSTOCKID"] == null ? 0 : Convert.ToInt64(item["FSTOCKID"]),
                    StockStatusID = item["FSTOCKSTATUSID"] == null ? 0 : Convert.ToInt64(item["FSTOCKSTATUSID"]),
                    OwnerTypeID = item["FOWNERTYPEID"]?.ToString() ?? "",
                    OwnerID = item["FOWNERID"] == null ? 0 : Convert.ToInt64(item["FOWNERID"]),
                    KeeperTypeID = item["FKEEPERTYPEID"]?.ToString() ?? "",
                    KeeperID = item["FKEEPERID"] == null ? 0 : Convert.ToInt64(item["FKEEPERID"]),
                    UnitID = item["FBASEUNITID"] == null ? 0 : Convert.ToInt64(item["FBASEUNITID"]),
                    BaseUnitID = item["FBASEUNITID"] == null ? 0 : Convert.ToInt64(item["FBASEUNITID"]),
                    SecUnitID = item["FSECUNITID"] == null ? 0 : Convert.ToInt64(item["FSECUNITID"]),
                    LockQty = lockQty,
                    LockBaseQty = lockQty,
                    //ReserveDate = DateTime.Now.AddDays(1000),
                    //ReserveDays = 1000,
                    //ReLeaseDate = DateTime.Now.AddDays(1000),
                    RequestNote = "订单审核锁库",
                    SupplyNote = "订单审核锁库",

                    // 可选字段
                    BillDetailID = "",
                    ProjectNo = "",
                    AuxPropId = 0,
                    Lot = 0,
                    LotNo = "",
                    StockLocID = 0
                };

                list.Add(stockArg);
                remainingQty -= lockQty; // 扣减剩余需求量
            }

            // 处理库存不足的预警（替换为实际日志实现）
            //if (remainingQty > 0)
            //{
            //    // 使用实际日志组件替换下面这行
            //    // Logger.Warn($"物料{matNumber}库存不足! 需求:{qty}, 实际锁定:{qty - remainingQty}");
            //    //System.Diagnostics.Debug.WriteLine($"物料{matNumber}库存不足! 需求:{qty}, 实际锁定:{qty - remainingQty}");
            //}
        }

        private DynamicObjectCollection GetInvInfo(long matId, long orgId, string mtoNo)
        {
            //T0.FID, 即时库存内码
            //T0.FSTOCKID, 仓库
            //T0.FSTOCKSTATUSID, 库存状态
            //T0.FBASEQTY, 基本数量
            //T0.FOWNERTYPEID, 货主类型
            //T0.FOWNERID, 货主
            //T0.FKEEPERTYPEID, 保管者类型
            //T0.FKEEPERID, 保管者
            //T0.FBASEUNITID, 基本单位
            //T0.FSECUNITID 库存辅单位
            string sql = string.Format(@"/*dialect*/ 
            select 
            T0.FID,
            T0.FSTOCKID,
            T0.FSTOCKSTATUSID,
            T0.FBASEQTY,
            T0.FOWNERTYPEID,
            T0.FOWNERID,
            T0.FKEEPERTYPEID,
            T0.FKEEPERID,
            T0.FBASEUNITID,
            T0.FSECUNITID
            from T_STK_INVENTORY t0
            WHERE T0.FBASEQTY>0 AND T0.FSTOCKORGID={0} AND T0.FMATERIALID={1} AND T0.FMTONO='{2}'  ", orgId, matId, mtoNo);
            DynamicObjectCollection doc = DBUtils.ExecuteDynamicObject(this.Context, sql);
            return doc;
        }

        private long GetDynamicValue(DynamicObject obj)
        {
            if (obj == null)
            {
                return 0L;
            }
            if (obj.DynamicObjectType.Properties.ContainsKey(FormConst.MASTER_ID))
            {
                return Convert.ToInt64(obj[FormConst.MASTER_ID]);
            }
            if (obj.DynamicObjectType.Properties.ContainsKey("Id"))
            {
                return Convert.ToInt64(obj["Id"]);
            }
            return 0L;
        }

        /// <summary>
        /// 添加操作返回信息
        /// </summary>
        private void AddOperateResult(IOperationResult operationResult, string message, string name)
        {
            IOperationResult opResult = new OperationResult();
            opResult.OperateResult.Add(new OperateResult()
            {
                SuccessStatus = true,
                Message = message,
                MessageType = MessageType.Normal,
                Name = name,
                PKValue = 0,
            });
            operationResult.MergeResult(opResult);
        }
    }
}
